import { Router } from 'express'
import expressWs from 'express-ws'

const router = Router()
expressWs(router)

const onlineUsers = []

router.ws('/serve', function (ws, req) {
  // 创建ws链接
  onlineUsers.push({ ws })
  ws.send('已连接到服务器')

  ws.on('message', function (msg) {
    ws.send('服务器收到')
  })

  ws.on('close', () => {
    ws.send('服务器断开')
    const index = onlineUsers.findIndex(({ ws: e }) => e == ws)
    if (index !== -1) onlineUsers.splice(index, 1)
  })
})

export default router
